package node.block.stmt;

import lexical.Word;
import midcode.MidCode;
import midcode.MidcodeGenerator;
import midcode.OPType;
import node.Node;
import node.exp.Exp;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PrintStmt implements Node {
    private final Word strcon;
    private final ArrayList<Exp> exps;

    public PrintStmt(Word strcon, ArrayList<Exp> exps) {
        this.strcon = strcon;
        this.exps = exps;
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String genMidCode() {
        MidcodeGenerator mg = MidcodeGenerator.getInstance();
        String formatStr = strcon.word;
        formatStr = formatStr.substring(1, formatStr.length() - 1);
        Pattern pattern = Pattern.compile("%d|[^%]*");
        Matcher matcher = pattern.matcher(formatStr);
        ArrayList<String> caledExp = new ArrayList<>();
        for (Exp exp : exps) {
            caledExp.add(exp.genMidCode());
        }
        int i = 0;
        while (matcher.find()) {
            if (matcher.group().equals("%d")) {
                mg.addMidcode(new MidCode(OPType.PRINT_INT, null, null, caledExp.get(i++)));
            } else if (!matcher.group().equals("")){
                mg.addMidcode(new MidCode(OPType.PRINT_STR, null, null, mg.genStr(matcher.group())));
            }
        }
        return "";
    }
}

